package com.chinasoft.goodsManager.servlet;

import com.chinasoft.goodsManager.domain.Goods;

import com.chinasoft.goodsManager.service.LoginService;
import com.chinasoft.goodsManager.service.impl.LoginServiceImpl;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import java.util.*;

@WebServlet("/goodsAdd")
public class GoodsAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LoginService loginService = new LoginServiceImpl();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Goods goods = new Goods();

        //文件上传解析器
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 判断enctype属性是否为multipart/form-data
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            try {
                //解析请求，将表单中每个输入项封装成一个FileItem对象
                List<FileItem> fileItems = upload.parseRequest(request);

                // 迭代表单数据
                for (FileItem fileItem : fileItems) {

                    //判断输入的类型是 普通输入项 还是文件
                    if (fileItem.isFormField()) {
                        if (fileItem.getString("UTF-8")!=null&&!fileItem.getString("UTF-8").equals("")){
//普通输入项 ,得到input中的name属性的值,fileItem.getFieldName()
                            ////得到输入项中的值,fileItem.getString("UTF-8"),"UTF-8"防止中文乱码
                            if (fileItem.getFieldName().equals("addgname")){
                                goods.setGname(fileItem.getString("UTF-8"));
                            }else if (fileItem.getFieldName().equals("addgnum")){
                                goods.setGnum(Integer.valueOf(fileItem.getString("UTF-8")));
                            }else if (fileItem.getFieldName().equals("addgpprice")){
                                goods.setGpprice(Double.parseDouble(fileItem.getString("UTF-8")));
                            }else if (fileItem.getFieldName().equals("addgprice")){
                                goods.setGprice(Double.parseDouble(fileItem.getString("UTF-8")));
                            }else if (fileItem.getFieldName().equals("addgdescrike")){
                                Date date = new Date();
                                OutputStreamWriter osv = new OutputStreamWriter(new FileOutputStream("D:\\GoodManagerFile\\GoodsFile\\"+date.getTime()+".txt"),"UTF-8");
                                osv.write(fileItem.getString("UTF-8"));
                                goods.setGdescrike(date.getTime()+".txt");
                                osv.close();
                            }
                        }
                    } else {
                        if (fileItem.getName().contains(".")){
                            //上传的是文件，获得文件上传字段中的文件名
                            //注意IE或FireFox中获取的文件名是不一样的，IE中是绝对路径，FireFox中只是文件名
                            String fileName = fileItem.getName();
                            //Substring是字符串截取，返回值是一个截取后的字符串
                            //lastIndexOf(".")是从右向左查,获取.之后的字符串
                            String ext = fileName.substring(fileName.lastIndexOf("."));
                            //UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法, UUID的唯一缺陷在于生成的结果串会比较长
                            String name = UUID.randomUUID()+ext;
                            String filename = "D:\\GoodManagerFile\\GoodsImg\\"+name;
                            goods.setGimg(name);
                            //将FileItem对象中保存的主体内容保存到某个指定的文件中
                            File file = new File(filename);
                            fileItem.write(file);
                        }
                    }
                }
                loginService.addGoods(goods);
                response.sendRedirect("GoodsList.html");
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("普通表单");
        }
      //  response.sendRedirect(request.getContextPath()+"/userList");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
